﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace ServerPlatform.Web
{
    
    public abstract class BaseDataEditor<T> : UserControl, IDataEditor<T> 
    {
        public delegate T OnCreateInstance();
        public event OnCreateInstance CreateInstance;
        private T current;

        #region IDataEditor<T> Members

        public virtual void Edit(T item)
        {
            ShowEntity(item);
            SaveEntity(item);
        }

        public virtual T EndEdit() 
        {
            return GetEntity();
        }

        public virtual void ClearCurrent()
        {
            ViewState["current"] = null;
        }

        public virtual void ClearEditor()
        {
            ;
        }

        protected abstract void ShowEntity(T entity);
        public abstract T GetEntity();

        protected virtual void SaveEntity(T entity) {
            ViewState["current"] = entity;
        }

        protected virtual void SaveEntity()
        {
            ViewState["current"] = Current;
        }

        protected virtual void ShowEntity()
        {
            ShowEntity(Current);
        }

        protected virtual T CreateDefaultInstance()
        {
            if (CreateInstance != null)
                return CreateInstance();
            else return Activator.CreateInstance<T>();
        }

        public T Current
        {
            get
            {
                if (current != null)
                    return current;
                else if (ViewState["current"] == null)
                {
                    current = CreateDefaultInstance();
                    return current;
                }
                else
                {
                    current = (T)ViewState["current"];
                    return current;
                }
            }
            set
            {
                ViewState["current"] = value;
                current = value;
            }
        }

        #endregion
    }
}
